//
//  LocationPickerViewController.m
//  StanfordEvents
//
//  Created by Gongmyung on 7/7/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LocationPickerViewController.h"


@implementation LocationPickerViewController

@synthesize delegate;

- (void)_coordinateChanged:(NSNotification *)notification {
	DDAnnotation *annotation = notification.object;
	
	if (self.reverseGeocoder) {
		[self.reverseGeocoder cancel];
		self.reverseGeocoder.delegate = nil;
		self.reverseGeocoder = nil;
	}
	
	// Note: If you lookup too many times within a very short of period, you might get error from Apple/Google.
	// e.g."/SourceCache/ProtocolBuffer/ProtocolBuffer-19/Runtime/PBRequester.m:446 server returned error: 503"
	// So you should avoid doing this in your code. This is just a demostration about how to reverse geocoding.
	self.reverseGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:annotation.coordinate];
	self.reverseGeocoder.delegate = self;
	[self.reverseGeocoder start];	
}

@synthesize annotations = _annotations;
@synthesize locationManager = _locationManager;
@synthesize reverseGeocoder = _reverseGeocoder;
@synthesize myMapView = myMapView;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];	
    
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(_coordinateChanged:)
												 name:@"DDAnnotationCoordinateDidChangeNotification" 
											   object:nil];	
    
	self.annotations = [[NSMutableSet alloc] initWithCapacity:1];
	
	// Start by locating current position
	self.locationManager = [[CLLocationManager alloc] init];
	self.locationManager.delegate = self;
	[self.locationManager startUpdatingLocation];	
    
    [myMapView setMapType:MKMapTypeStandard];
    [myMapView setZoomEnabled:YES];
    [myMapView setScrollEnabled:YES];
    [myMapView setShowsUserLocation:YES];
    
    
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc]
                                     initWithTitle:NSLocalizedString(@"Cancel", @"Cancel - for button to cancel changes")
                                     style:UIBarButtonItemStylePlain
                                     target:self
                                     action:@selector(cancel)];
    self.navigationItem.leftBarButtonItem = cancelButton;
    [cancelButton release];
    UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]
                                   initWithTitle:NSLocalizedString(@"Save", @"Save - for button to save changes")
                                   style:UIBarButtonItemStylePlain
                                   target:self
                                   action:@selector(save)];
    self.navigationItem.rightBarButtonItem = saveButton;
    [saveButton release];
    
    self.title = @"Pick a Location";
}

-(IBAction)cancel
{
    [[self.delegate navController] popViewControllerAnimated:YES];
}

-(IBAction)save
{
    DDAnnotation *annotation = [_annotations anyObject];
    
    //TODO pass back actual location
    [self.delegate setLocation:annotation.subtitle withLatitude:annotation.coordinate.latitude withLogitude:annotation.coordinate.longitude];
    [[self.delegate navController] popViewControllerAnimated:YES];
}

//delegate method
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    for (MKAnnotationView *annotationView in views) {
        if (annotationView.annotation == mapView.userLocation) {
            MKCoordinateSpan span = MKCoordinateSpanMake(0.01, 0.02);
            MKCoordinateRegion region = MKCoordinateRegionMake(mapView.userLocation.coordinate, span);
            [mapView setRegion:region animated:YES];
			[mapView regionThatFits:region];
        }
    }
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark CLLocationManagerDelegate methods

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	
	// Add annotation to map
	DDAnnotation *annotation = [[DDAnnotation alloc] initWithCoordinate:newLocation.coordinate addressDictionary:nil];
	annotation.title = @"Drag to move Pin";
	[self.annotations addObject:annotation];
	[self.myMapView addAnnotation:annotation];
	[annotation release];
    
	// We only update location once, and let users to do the rest of the changes by dragging annotation to place they want
	[manager stopUpdatingLocation];
}


#pragma mark -
#pragma mark MKMapViewDelegate methods

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
	
	if (annotation == mapView.userLocation) {
		return nil;
	}
	
	DDAnnotationView *annotationView = (DDAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"Pin"];
	if (annotationView == nil) {
		annotationView = [[[DDAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Pin"] autorelease];
	}
	// Dragging annotation will need _mapView to convert new point to coordinate;
	annotationView.mapView = mapView;
	
	//annotationView.leftCalloutAccessoryView
	
	UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
	annotationView.rightCalloutAccessoryView = rightButton;		
	
	return annotationView;
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
	if ([control isKindOfClass:[UIButton class]]) {		
		UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Enter Description (Gates 307)" message:@"canceling..." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        myTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
        [myTextField setBackgroundColor:[UIColor whiteColor]];
        [myAlertView addSubview:myTextField];
        [myAlertView show];
        [myAlertView release];
	}
}

//alert view delegate methods
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if( buttonIndex == 1 ) {
        for (DDAnnotation *annotation in _annotations) {
            annotation.subtitle = myTextField.text;
        }
    }
    [myTextField release];
}

#pragma mark -
#pragma mark Notification and ReverseGeocoding

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)newPlacemark {
	for (DDAnnotation *annotation in _annotations) {
		if (annotation.coordinate.latitude == geocoder.coordinate.latitude && annotation.coordinate.longitude == geocoder.coordinate.longitude) {
			annotation.subtitle = [[newPlacemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
		}
	}
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
	for (DDAnnotation *annotation in _annotations) {
		if (annotation.coordinate.latitude == geocoder.coordinate.latitude && annotation.coordinate.longitude == geocoder.coordinate.longitude) {
			annotation.subtitle = nil;
		}
	}
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    self.myMapView.delegate = nil;
	self.myMapView = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
	
	for (DDAnnotation *annotation in _annotations) {
		[myMapView removeAnnotation:annotation];
		[annotation release];
	}
	myMapView.delegate = nil;
	[myMapView release];
	myMapView = nil;
	
	[_annotations release];
	_annotations = nil;		
	
	_locationManager.delegate = nil;
	[_locationManager release];
	_locationManager = nil;
    [super dealloc];
}


@end
